package com.yserp.rlzy_gz.controller;
import com.yserp.rlzy_gz.entity.TLxjjEntity;
import com.yserp.rlzy_gz.entity.TPayEntity;
import com.yserp.rlzy_gz.service.TPayServiceI;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.core.util.*;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.common.TreeChildCount;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.service.SystemService;

import java.io.OutputStream;

import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.entity.vo.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.vo.TemplateExcelConstants;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.IOException;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import java.util.Map;
import java.util.HashMap;

import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;
import org.springframework.http.MediaType;
import org.springframework.web.util.UriComponentsBuilder;
import org.apache.commons.lang3.StringUtils;
import org.jeecgframework.jwt.util.GsonUtil;
import org.jeecgframework.jwt.util.ResponseMessage;
import org.jeecgframework.jwt.util.Result;
import com.alibaba.fastjson.JSONArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**   
 * @Title: Controller  
 * @Description: 薪点奖金工资
 * @author onlineGenerator
 * @date 2018-06-29 12:53:15
 * @version V1.0   
 *
 */
@Api(value="TPay",description="薪点奖金工资",tags="tPayController")
@Controller
@RequestMapping("/tPayController")
public class TPayController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(TPayController.class);

	@Autowired
	private TPayServiceI tPayService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;
	


	/**
	 * 薪点奖金工资列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("com/yserp/rlzy_gz/tPayList");
	}
	@RequestMapping(params = "rzbi")
	public ModelAndView rzbi(HttpServletRequest request) {

		TSUser user = ResourceUtil.getSessionUser();
		request.setAttribute("user", user);
		request.setAttribute("depname",user.getCurrentDepart().getDepartname());
		request.setAttribute("rennum",user.getUserName());
		request.setAttribute("dqyf","0.00");//当前月份
		request.setAttribute("byyf","0.00");//当月应发
		request.setAttribute("bysf","0.00");//当月实发
		request.setAttribute("dnsf","0.00");//当年实发
		request.setAttribute("dnyf","0.00");//当月实发
		double jiangjin = 0.00;
		double byyf = 0.00;
		double bysf =0.00;
		try{
			String hql = " from TPayEntity where rzNum = ? order by id  desc";
			TPayEntity tpay =null;
			tpay = (TPayEntity)systemService.findHql(hql,user.getUserName()).get(0);
			if(tpay!=null){

				if(!StringUtil.isEmpty(tpay.getLxjj())){
					jiangjin =  jiangjin + Double.parseDouble(tpay.getLxjj());
				}
				if(!StringUtil.isEmpty(tpay.getYj1())){
					jiangjin =  jiangjin + Double.parseDouble(tpay.getYj1());
				}
				if(!StringUtil.isEmpty(tpay.getYj2())){
					jiangjin =  jiangjin + Double.parseDouble(tpay.getYj2());
				}
				if(!StringUtil.isEmpty(tpay.getYj3())){
					jiangjin =  jiangjin + Double.parseDouble(tpay.getYj3());
				}
				bysf = jiangjin + Double.parseDouble(tpay.getSfTotal());
				byyf = jiangjin + Double.parseDouble(tpay.getYfTotal());
				request.setAttribute("dqyf",tpay.getGzDate());//当前月份
				DecimalFormat df   = new DecimalFormat("######0.00");
				request.setAttribute("byyf",df.format(byyf));//当月应发
				request.setAttribute("bysf",df.format(bysf));//当月实发
				request.setAttribute("tPayPage", tpay);//
			}
		}catch (Exception e){

		}
		try{
			StringBuffer sb = new StringBuffer();
			sb.append("select round((sum(ifnull(sf_total,0)) + sum( ifnull(lxjj,0)) + sum(ifnull(yj1,0))+ sum(ifnull(yj2,0)) + sum(ifnull(yj3,0)) ),2) as ydtotal from  t_pay where gz_date like ? and rz_Num= ?");
			List<Map<String,Object>> maplist =systemService.findForJdbc(sb.toString(), "%"+DateUtils.date2Str(DateUtils.date_sdfny)+"%",user.getUserName());

			if (maplist.size() > 0) {
				for (Map<String,Object> object : maplist) {
					if(!StringUtil.isEmpty(object.get("ydtotal").toString())){
						request.setAttribute("dnsf",object.get("ydtotal").toString());
					}
				}
				}
		}catch (Exception e){

		}

		try{
			StringBuffer sbdn = new StringBuffer();
			sbdn.append("select round((sum(ifnull(yf_total,0)) + sum( ifnull(lxjj,0)) + sum(ifnull(yj1,0))+ sum(ifnull(yj2,0)) + sum(ifnull(yj3,0)) ),2) as ydtotal from  t_pay where gz_date like ? and rz_Num= ?");
			List<Map<String,Object>> maplistdn =systemService.findForJdbc(sbdn.toString(), "%"+DateUtils.date2Str(DateUtils.date_sdfny)+"%",user.getUserName());
			if (maplistdn.size() > 0) {
				for (Map<String,Object> object : maplistdn) {
					if(!StringUtil.isEmpty(object.get("ydtotal").toString())) {
						request.setAttribute("dnyf", object.get("ydtotal").toString());
					}
				}
			}
		}catch (Exception e){

		}
		return new ModelAndView("com/yserp/rlzy_gz/rzbi");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(TPayEntity tPay,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TPayEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tPay, request.getParameterMap());
		try{
		//自定义追加查询条件
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.tPayService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	@RequestMapping(params = "listgr")
	public ModelAndView listgr(HttpServletRequest request) {
		return new ModelAndView("com/yserp/rlzy_gz/tPayListgr");
	}
	@RequestMapping(params = "datagridgr")
	public void datagridgr(TPayEntity tPay,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(TPayEntity.class, dataGrid);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tPay, request.getParameterMap());
		Double sumyf = 0.00;
		Double sumsf = 0.00;
		try{
			//自定义追加查询条件
			TSUser user = ResourceUtil.getSessionUser();
//			if(user.getUserKey().)
			cq.eq("rzNum",user.getUserName());
		}catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		cq.add();
		this.tPayService.getDataGridReturn(cq, true);


		List<TPayEntity> res = dataGrid.getResults();
		for(TPayEntity t:res){
			sumyf = sumyf + Double.parseDouble(t.getYfTotal());
			sumsf = sumsf + Double.parseDouble(t.getSfTotal());
		}
		dataGrid.setFooter("person:合计,"+"yfTotal:"+sumyf.toString()+","+"sfTotal:"+sumsf.toString());
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除薪点奖金工资
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(TPayEntity tPay, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		tPay = systemService.getEntity(TPayEntity.class, tPay.getId());
		message = "薪点奖金工资删除成功";
		try{
			tPayService.delete(tPay);
			systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "薪点奖金工资删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除薪点奖金工资
	 * 
	 * @return
	 */
	 @RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids,HttpServletRequest request){
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "薪点奖金工资删除成功";
		try{
			for(String id:ids.split(",")){
				TPayEntity tPay = systemService.getEntity(TPayEntity.class, 
				Integer.parseInt(id)
				);
				tPayService.delete(tPay);
				systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
			}
		}catch(Exception e){
			e.printStackTrace();
			message = "薪点奖金工资删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加薪点奖金工资
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(TPayEntity tPay, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "薪点奖金工资添加成功";
		try{
			tPayService.save(tPay);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "薪点奖金工资添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 更新薪点奖金工资
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(TPayEntity tPay, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		message = "薪点奖金工资更新成功";
		TPayEntity t = tPayService.get(TPayEntity.class, tPay.getId());
		try {
			MyBeanUtils.copyBeanNotNull2Bean(tPay, t);
			tPayService.saveOrUpdate(t);
			systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "薪点奖金工资更新失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	

	/**
	 * 薪点奖金工资新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(TPayEntity tPay, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(tPay.getId())) {
			tPay = tPayService.getEntity(TPayEntity.class, tPay.getId());
			req.setAttribute("tPayPage", tPay);
		}
		return new ModelAndView("com/yserp/rlzy_gz/tPay-add");
	}
	/**
	 * 薪点奖金工资编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(TPayEntity tPay, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(tPay.getId())) {
			tPay = tPayService.getEntity(TPayEntity.class, tPay.getId());
			req.setAttribute("tPayPage", tPay);
		}
		return new ModelAndView("com/yserp/rlzy_gz/tPay-update");
	}
	
	/**
	 * 导入功能跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "upload")
	public ModelAndView upload(HttpServletRequest req) {
		req.setAttribute("controller_name","tPayController");
		return new ModelAndView("common/upload/pub_excel_upload");
	}
	
	/**
	 * 导出excel
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXls")
	public String exportXls(TPayEntity tPay,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
		CriteriaQuery cq = new CriteriaQuery(TPayEntity.class, dataGrid);
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, tPay, request.getParameterMap());
		List<TPayEntity> tPays = this.tPayService.getListByCriteriaQuery(cq,false);
		modelMap.put(NormalExcelConstants.FILE_NAME,"薪点奖金工资");
		modelMap.put(NormalExcelConstants.CLASS,TPayEntity.class);
		modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("薪点奖金工资列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
			"导出信息"));
		modelMap.put(NormalExcelConstants.DATA_LIST,tPays);
		return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	/**
	 * 导出excel 使模板
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(params = "exportXlsByT")
	public String exportXlsByT(TPayEntity tPay,HttpServletRequest request,HttpServletResponse response
			, DataGrid dataGrid,ModelMap modelMap) {
    	modelMap.put(NormalExcelConstants.FILE_NAME,"薪点奖金工资");
    	modelMap.put(NormalExcelConstants.CLASS,TPayEntity.class);
    	modelMap.put(NormalExcelConstants.PARAMS,new ExportParams("薪点奖金工资列表", "导出人:"+ResourceUtil.getSessionUser().getRealName(),
    	"导出信息"));
    	modelMap.put(NormalExcelConstants.DATA_LIST,new ArrayList());
    	return NormalExcelConstants.JEECG_EXCEL_VIEW;
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(params = "importExcel", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson importExcel(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j = new AjaxJson();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			Double sum = 0.00;
			try {
				List<TPayEntity> listTPayEntitys = ExcelImportUtil.importExcel(file.getInputStream(),TPayEntity.class,params);
				for (TPayEntity tPay : listTPayEntitys) {

					String hql = " from TPayEntity where gzDate = ? and rzNum = ? ";
					TPayEntity t =null;
					try{
						try{
							t = (TPayEntity)systemService.findHql(hql,tPay.getGzDate(),tPay.getRzNum()).get(0);

						}catch (Exception e){

						}
						if(t!=null){
							MyBeanUtils.copyBeanNotNull2Bean(tPay, t);
							tPayService.updateEntitie(t);
						}else{
							tPayService.save(tPay);
						}
					}catch (Exception e){
					}

					try{
						sum = sum + Double.parseDouble(tPay.getYfTotal());
					}catch (Exception e){

					}


				}
				DecimalFormat df   = new DecimalFormat("######0.00");
				j.setMsg("文件导入成功！工资应发总计："+df.format(sum));
			} catch (Exception e) {
				j.setMsg("文件导入失败！");
				logger.error(ExceptionUtil.getExceptionMessage(e));
			}finally{
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return j;
	}
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="薪点奖金工资列表信息",produces="application/json",httpMethod="GET")
	public ResponseMessage<List<TPayEntity>> list() {
		List<TPayEntity> listTPays=tPayService.getList(TPayEntity.class);
		return Result.success(listTPays);
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value="根据ID获取薪点奖金工资信息",notes="根据ID获取薪点奖金工资信息",httpMethod="GET",produces="application/json")
	public ResponseMessage<?> get(@ApiParam(required=true,name="id",value="ID")@PathVariable("id") String id) {
		TPayEntity task = tPayService.get(TPayEntity.class, id);
		if (task == null) {
			return Result.error("根据ID获取薪点奖金工资信息为空");
		}
		return Result.success(task);
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value="创建薪点奖金工资")
	public ResponseMessage<?> create(@ApiParam(name="薪点奖金工资对象")@RequestBody TPayEntity tPay, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<TPayEntity>> failures = validator.validate(tPay);
		if (!failures.isEmpty()) {
			return Result.error(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}

		//保存
		try{
			tPayService.save(tPay);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("薪点奖金工资信息保存失败");
		}
		return Result.success(tPay);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	@ApiOperation(value="更新薪点奖金工资",notes="更新薪点奖金工资")
	public ResponseMessage<?> update(@ApiParam(name="薪点奖金工资对象")@RequestBody TPayEntity tPay) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<TPayEntity>> failures = validator.validate(tPay);
		if (!failures.isEmpty()) {
			return Result.error(JSONArray.toJSONString(BeanValidators.extractPropertyAndMessage(failures)));
		}

		//保存
		try{
			tPayService.saveOrUpdate(tPay);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("更新薪点奖金工资信息失败");
		}

		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return Result.success("更新薪点奖金工资信息成功");
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	@ApiOperation(value="删除薪点奖金工资")
	public ResponseMessage<?> delete(@ApiParam(name="id",value="ID",required=true)@PathVariable("id") String id) {
		logger.info("delete[{}]" + id);
		// 验证
		if (StringUtils.isEmpty(id)) {
			return Result.error("ID不能为空");
		}
		try {
			tPayService.deleteEntityById(TPayEntity.class, id);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("薪点奖金工资删除失败");
		}

		return Result.success();
	}
}
